package com.sinoglobal.ningxia.activity.easyfun;

import android.app.Service;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ImageView;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.vip.Login;
import com.sinoglobal.ningxia.beans.EasyFunBeginVo;
import com.sinoglobal.ningxia.beans.EasyFunEndVo;
import com.sinoglobal.ningxia.dialog.DialogBuilder;
import com.sinoglobal.ningxia.dialog.MDialogMethod;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.AbstractActivity;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;

import net.tsz.afinal.FinalBitmap;

/**
 * 
 * @author yrq
 * @createdate 2014-7-21 下午1:23:49
 * @Description:乐逍遥
 */
public class EasyfunActivity extends AbstractActivity implements
		SensorEventListener {
	private Vibrator Vibrator;
	private SensorManager sensorManager;
	private boolean flag = false; // 判断当是否可以摇动
	private String esayFunId = ""; // 活动id
	private ImageView bg;
	private ImageView back;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isTemplate = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_easyfun);
		init();
		showListener();
	}

	private void init() {
		bg = (ImageView) findViewById(R.id.easy_fun_bg);
		back = (ImageView) findViewById(R.id.title_but_left);
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // 获取系统的传感器服务
		Vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); // 获取系统的震动服务
		getBeginMessage();
	}

	private void showListener() {
		back.setOnClickListener(new android.view.View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && data.getIntExtra("login", 0) == 1) { // 登录成功
			flag = true; // flag = true 摇动时无任何效果有震动效果 执行请求摇动结果的代码
			sensorManager.registerListener(EasyfunActivity.this,
					sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
					SensorManager.SENSOR_DELAY_NORMAL);
		}
	}

	/**
	 * 摇奖初始化数据 能不能摇奖
	 */
	private void getBeginMessage() {
		new ItktAsyncTaskWithDialog<Void, Void, EasyFunBeginVo>(getString(R.string.loading_prize_data),
				true, true) {

			@Override
			public EasyFunBeginVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getEasyFunBeginInfo(
						FlyApplication.userId);
			}

			@Override
			public void after(EasyFunBeginVo result) {
				if (result.getCode() == Code.CODE_SUCCESS) { // 有活动
					FinalBitmap fb = FinalBitmap.create(EasyfunActivity.this);
					fb.configLoadfailImage(R.drawable.img_easyfun_bg);
					fb.configLoadingImage(R.drawable.img_easyfun_bg);
					fb.display(bg, ConnectionUtil.localUrl + result.getImage());
					esayFunId = result.getId(); // 活动id
					if ("1".equals(result.getStatus())) { // 已摇过
						if (!EasyfunActivity.this.isFinishing()) {
							showDialogMode(getString(R.string.has_do_prize), 1);
						}
					}
					if ("2".equals(result.getStatus())) {
						final DialogBuilder dialogBuilder = new DialogBuilder(
								EasyfunActivity.this);
						dialogBuilder.Dialogbtn2(getString(R.string.no_login),
								R.layout.dialog_two_button,
								new MDialogMethod() {

									@Override
									public void dialogOk() {
										Intent intent = new Intent(
												EasyfunActivity.this,
												Login.class);
										startActivityForResult(intent, 0);
										dialogBuilder.mdialog.dismiss();
									}

									@Override
									public void dialogCancel() {
										dialogBuilder.mdialog.dismiss();
									}
								});
					}
					if ("0".equals(result.getStatus())) { // 未摇过
						flag = true; // flag = true 摇动时无任何效果有震动效果 执行请求摇动结果的代码
						sensorManager
								.registerListener(
										EasyfunActivity.this,
										sensorManager
												.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
										SensorManager.SENSOR_DELAY_NORMAL);
					}
				}
				if (result.getCode() == Code.CODE_NOACTIVIVTY) { // 无活动
					showDialogMode(result.getMessage(), 1);
				}
			}

			@Override
			public void exception() {
			}
		}.execute();
	}

	/**
	 * 显示提示对话框
	 * 
	 * @param messageString
	 *            提示信息
	 * @param type
	 *            标志
	 */
	private void showDialogMode(String messageString, final int type) {
		final DialogBuilder dialogBuilder = new DialogBuilder(
				EasyfunActivity.this);
		dialogBuilder.Dialogbtn1(messageString, R.layout.dialog_one_button,
				new MDialogMethod() {

					@Override
					public void dialogOk() {
						if (type == 2) {
							flag = true;// flag = true 摇动时无任何效果有震动效果执行请求摇动结果的代码
						}
						dialogBuilder.mdialog.dismiss();
					}

					@Override
					public void dialogCancel() {
					}
				});
	}

	
	 //获取得奖信息
	private void getEndMessage() {
		new ItktAsyncTaskWithDialog<Void, Void, EasyFunEndVo>(getString(R.string.loading_prize_result),
				true, true) {

			@Override
			public EasyFunEndVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getEasyFunEndInfo(esayFunId,
						FlyApplication.userId);
			}

			@Override
			public void after(EasyFunEndVo result) {
				if (result != null) {
					showDialogMode(result.getMessage(), 2);
				}
			}

			@Override
			public void exception() {
			}
		}.execute();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){
			  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			 }
	}
	@Override
	protected void onRestart() {
		super.onRestart();
		flag = true; // flag = true 摇动时无任何效果有震动效果 执行请求摇动结果的代码
	}

	@Override
	protected void onStop() {
		super.onStop();
		flag = false; // flag = false 摇动时无任何效果 不执行请求摇动结果的代码
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (sensorManager != null) {// 取消监听器
			sensorManager.unregisterListener(EasyfunActivity.this);
		}
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		int sensorType = event.sensor.getType();
		// values[0]:X轴，values[1]：Y轴，values[2]：Z轴
		float[] values = event.values;
		if (sensorType == Sensor.TYPE_ACCELEROMETER) { // 判断传感器类型是否是加速度类型
			// 值[0]:x轴上的加速度- Gx
			// 值[1]:加速度减去沿着y轴Gy
			// 值[2]:加速度-广州在z轴的
			if ((Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math
					.abs(values[2]) > 14)) {
				// 摇动手机后，再伴随震动提示~~
				if (flag) {
					flag = false; // flag = true 摇动时无任何效果有震动效果 执行请求摇动结果的代码
					Vibrator.vibrate(500);
					getEndMessage();
				}
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}
}
